
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
        <!-- 添加商品信息提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>
      <!-- 进度条 activeIndex - 0 是将字符串转换成数字 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- Tab选项标签页 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormReF" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="addBeforeLeave" @tab-click="tabClicked">
              <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop="goods_name">
                  <el-input v-model="addForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                  <el-input v-model="addForm.goods_price" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="goods_weight">
                  <el-input v-model="addForm.goods_weight" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="goods_number">
                  <el-input v-model="addForm.goods_number" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="goods_cat">
                  <!-- 级联选择框 -->
                    <!-- v-model 被选中的父级分类id数组 -->
                    <!-- options  绑定的数据源-->
                    <!-- props 配置对象，决定了前台要接收和显示的对象。 -->
                    <!-- checkStrictly 控制级联多选或单选 -->
                    <!-- show-all-levels 控制级联选择器是否显示完整路径 -->
                   <el-cascader
                        v-model="addForm.goods_cat"
                        :options="addCateList"
                        :props="{ 
                            expandTrigger: 'hover',
                            value: 'cat_id',
                            label: 'cat_name',
                            children: 'children',
                            checkStrictly: false
                        }"
                        @change="handleChange" clearable show-all-levels>
                    </el-cascader>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品参数" name="1">
                <el-form-item :label="item.attr_name" v-for="item in manyTableDate" :key="item.attr_id">
                  <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品属性" name="2">
                <el-form-item :label="item.attr_name" v-for="item in nolyTableDate" :key="item.attr_id">
                  <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品图片" name="3">
                <!-- action 表示图片要上传到的api地址 -->
                <!-- on-preview 处理预览的业务逻辑 点击预览触发事件 -->
                <!-- on-remove 点击上传图片右上角的叉触发事件 -->
                <!-- file-list 选择文件列表 直接在电脑选择上传图片使用不到暂时删除-->
                <!-- list-type 预览图片的呈现方式 -->
                <el-upload 
                  action="http://127.0.0.1:8888/api/private/v1/upload"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  list-type="picture" :headers="headerObj" :on-success="handleSuccess">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-tab-pane>
              <el-tab-pane label="商品内容" name="4">
                <quill-editor :v-model="addForm.goods_introduce"></quill-editor>
                <el-button type="primary" class="btnadd" @click="add">添加商品</el-button>
              </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览窗口 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%">
      <img :src="previewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
        // 进度条索引
        activeIndex: '0',
        // 添加商品按钮的表单数据对象
        addForm: {
          goods_name: '',
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          // 商品所属分类列表
          goods_cat: [],
          // 图片上传成功的数组
          pics: [],
          // 商品详情
          goods_introduce: '',
          // 需要提交的属性和参数数组
          attrs: []
        },
        // 添加商品按钮的表单验证
        addFormRules: {
          goods_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
          goods_price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' }
                    
                ],
          goods_weight: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' }
                   
                ],
          goods_number: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' }
                    
                ],
          goods_cat: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' }
                    
                ]                         
        },
        // 级联选择器商品分类数据
        addCateList: [],
        // 获取的动态参数数据 many
        manyTableDate: [],
        // 获取的静态属性数据 noly
        nolyTableDate: [],
        // 图片上传的请求头
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        // 获取图片url
        previewPath: '',
        previewVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if(res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      //  console.log(res)
       this.addCateList = res.data
    },
    handleChange() {
      if(this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // activeName即将进入的标签页名称
    // oldActiveName即将离开的标签页名称
    addBeforeLeave(activeName, oldActiveName) {
      if(oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    async tabClicked() {
      if(this.activeIndex === '1') {
          const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: {
          sel: 'many'
          } }) 
          if(res.meta.status !== 200) {
            return this.$message.error('获取数据失败')
          }
          res.data.forEach(item => {
              item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          })
          // console.log(res.data)
          this.manyTableDate = res.data
      } else if(this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: {
          sel: 'only'
          } }) 
          if(res.meta.status !== 200) {
            return this.$message.error('获取数据失败')
          }
          // res.data.forEach(item => {
          //     item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          // })
          this.nolyTableDate = res.data
          // console.log(res.data)
      }
    },
    // 图片上传点击预览触发
    handlePreview(file) {
      this.previewPath = file.response.data.url
      console.log(file)
      this.previewVisible = true
    },
    // 点击上传图片的叉子触发事件
    handleRemove(file) {
      // 获取将要删除的图片路径
      const filepath = file.response.data.tmp_path
      // 从pics数组中找到要删除图片的索引值
      const i = this.addForm.pics.findIndex(x => x.pic === filepath)
      // 删除数组中的元素
      this.addForm.pics.splice(i, 1)
    },
    // 上传图片成功立即调用response 服务器返回的数据 file 文件信息 filelist 当前文件上传列表
    handleSuccess(response) {
      // 1先拼接得到一个信息对象
      const picInfo = { pic: response.data.tmp_path } 
      // 2将图片信息对象push到数组中
      this.addForm.pics.push(picInfo)
      console.log(this.addForm)
    },
    add() {
      // 验证
      this.$refs.addFormReF.validate(async valid => {
        if(!valid) return this.$message.error('请填写必填项')
        // 复制一份this.addForm 
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTableDate.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // // 处理静态属性
        this.nolyTableDate.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        // console.log(form)
        const { data: res } = await this.$http.post('goods', form)
        if(res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods~')
      })
    }
  },
  computed: {
    cateId() {
      if(this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }  
}    
</script>

<style lang="less" scoped>
.el-steps {
    margin: 15px 0;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.btnadd{
  margin-top: 15px;
}
</style>
